package cn.xspace.app.filemg.util;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.DisplayMetrics;

import com.xspace.android.xafcommon.db.dbsub.BaseDbMg;
import com.xspace.android.xafcommon.util.DateUtils;
import com.xspace.android.xafcommon.util.LogUtil;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

import cn.xspace.app.filemg.bean.FileInfo;
import cn.xspace.app.filemg.bean.ImgPackInfo;

public class QueryFileMg {
	String fileName;
	FileInfo videoInfo;
	FileInfo info;
	String parent;
	ImgPackInfo imgInfo;
	FileInfo docInfo;
	FileInfo othreInfo;
	// FileInfo apkInfo;
	FileInfo musicInfo;
	ArrayList<ImgPackInfo> imgPackList = new ArrayList<ImgPackInfo>();
	ArrayList<FileInfo> docList = new ArrayList<FileInfo>();
	ArrayList<FileInfo> musicList = new ArrayList<FileInfo>();
	ArrayList<FileInfo> mvList = new ArrayList<FileInfo>();
	ArrayList<FileInfo> apkList = new ArrayList<FileInfo>();
	ArrayList<FileInfo> otherFileList = new ArrayList<FileInfo>();
	private Context mContext;
    private List<PackageInfo> pinfo;
	public QueryFileMg(Context mContext) {
		this.mContext = mContext;
		new MyAsyncTask().execute();
	}

	private class MyAsyncTask extends AsyncTask {
		@Override
		protected Object doInBackground(Object... arg0) {
			// TODO Auto-generated method stub
			queryFile();
//			getLocalSdCardApk(sdCardFile);
			// queryFileAll();
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			LogUtil.v("queryFile", "-------------------onPostExecute--");
			LogUtil.v("queryFile","---------------------docList:" + docList.size());
			LogUtil.v("queryFile","---------------------apkList:" + apkList.size());
			LogUtil.v("queryFile","---------------------otherFileList:" + otherFileList.size());
			// BaseDbMg.getInstance().getSendSql().delete("img");
			//
			BaseDbMg.getInstance().getFileMgDb().delete("doc");
			BaseDbMg.getInstance().getFileMgDb().delete("apk");
			 BaseDbMg.getInstance().getFileMgDb().delete("other");

			// BaseDbMg.getInstance().getFileMgDb()
			// .saveOrUpdateImg("img", imgPackList);

			BaseDbMg.getInstance().getFileMgDb().saveOrUpdate("doc", docList);
			BaseDbMg.getInstance().getFileMgDb().saveOrUpdate("apk", apkList);
			BaseDbMg.getInstance().getFileMgDb().saveOrUpdate("other", otherFileList);
			// BaseDbMg.getInstance().getFileMgDb().saveOrUpdate("mv", mvList);
		}

	}

	private boolean findFlag = true;

	private void queryFileAll() {
		try {
			Map<String, String> map = System.getenv();
			Set<String> set = map.keySet();
			Iterator<String> key = set.iterator();
			while (key.hasNext()) {
				if (!findFlag) {
					return;
				}
				Collection<String> col = map.values();
				Iterator<String> val = col.iterator();
				key.next();
				A: while (val.hasNext()) {

					if (!findFlag) {
						return;
					}
					String sdcard = val.next();
					if (sdcard.indexOf("sdcard") < 0
							&& sdcard.indexOf("storage") < 0) {
						continue;
					}
					File f = new File(sdcard);
					File[] files = f.listFiles();
					if (files != null) {
						if (!findFlag) {
							return;
						}
						boolean flag = true;
						B: for (int i = 0; i < files.length; i++) {

							try {
								File file = files[i];
								if (file.isFile()) {
									fileName = file.getName();
									// if (fileName.endsWith(".mp3")) {
									// addMusicInfo(file);
									// } else
									if (fileName.endsWith(".doc")
											|| fileName.endsWith(".pdf")
											|| fileName.endsWith(".txt")
											|| fileName.endsWith(".ebk3")) {
										addDocInfo(file);
									} else if (file.getName().endsWith(".apk")) {
										addApkInfo(file);
									}

									// else if (fileName.endsWith(".mp4")
									// || fileName.endsWith(".rmvb")) {
									// addVideoInfo(file);
									// } else if (flag
									// && fileName.endsWith(".jpg")) {
									// addImgInfo(file);
									// flag = false;
									// }

								} else if (file.isDirectory()
										&& file.listFiles().length > 0) {
									if (file.getPath().indexOf(".") < 0) {
										queue.offer(file.getPath());
									}
								}
							} catch (Exception e) {

							}
						}
						String str;
						try {
							while ((str = queue.poll()) != null) {
								// System.out.println(str);
								if (!findFlag) {
									return;
								}
								try {
									childPath(new File(str));
								} catch (Exception e) {
									System.out.println("-----------"
											+ e.getMessage());
								}

							}
						} catch (Exception e) {
						}
						if (!findFlag) {
							return;
						}
					}
				}
			}
		} catch (Exception e) {
			System.out.println("-------------------22222--" + e.getMessage());

		} finally {
			System.out.println("-------------------333333--");
			// handler.sendEmptyMessageDelayed(0, 1000);
		}
	}

	private Queue<String> queue = new LinkedList<String>();

	private synchronized void childPath(File sdPath) {
		String path = sdPath.getPath();
		// if (path.indexOf("DCIM") >= 0 || path.indexOf("music") >= 0
		// || path.indexOf("book") >= 0 || path.indexOf("read") >= 0
		// || path.indexOf("mp3") >= 0 || path.indexOf("emulated") >= 0
		// || path.indexOf("download") >= 0
		// || path.indexOf("NetworkSpeeder") >= 0) {

		for (File file : sdPath.listFiles()) {
			if (file.isFile()) {
				System.out.println("---------file.getName():" + file.getPath());
				// if (file.getName().endsWith(".mp3")) {
				// addMusicInfo(file);
				// } else
				if (file.getName().endsWith(".doc")
						|| file.getName().endsWith(".pdf")
						|| file.getName().endsWith(".txt")) {
					addDocInfo(file);
				}
				//
				// else if (file.getName().endsWith(".mp4")
				// || file.getName().endsWith(".rmvb")) {
				// addVideoInfo(file);
				// } else if (file.getName().endsWith(".jpg")) {
				// addImgInfo(file);
				// }
				else if (file.getName().endsWith(".apk")) {
					addApkInfo(file);
				}

			} else if (file.isDirectory() && file.listFiles().length > 0) {
				if (file.getPath().indexOf(".") < 0) {
					queue.offer(file.getPath());
				}
			}
		}

		// } else {
		// for (File file : sdPath.listFiles()) {
		// if (file.isDirectory() && file.listFiles().length > 0
		// && file.getPath().split("/").length <= 4) {
		// if (file.getPath().indexOf(".") < 0) {
		// queue.offer(file.getPath());
		// }
		// }
		// }
		// }
	}

	private void queryFile() {
		LogUtil.v("queryFile","begin>>>>>>>>>>>>>>>>>" );
		long begintime=System.currentTimeMillis();
		try {
			Map<String, String> map = System.getenv();
			Set<String> set = map.keySet();
			Iterator<String> key = set.iterator();
			int mapSize = map.size();
			while (key.hasNext()) {
				Collection<String> col = map.values();
				Iterator<String> val = col.iterator();
				key.next();
				while (val.hasNext()) {
					String sdcard = val.next();// ""+android.os.Environment.getExternalStorageDirectory();
					//LogUtil.v("queryFile","-------------------sdcard--" + sdcard);
					if (sdcard.indexOf("sdcard") >= 0
							|| sdcard.indexOf("storage") >=0) {
					File f = new File(sdcard);
					File[] files = f.listFiles();
					if (files != null) {
						for (int i = 0; i < files.length; i++) {
							try {
								final File file = files[i];
								if (file.isFile()) {
									fileName = file.getName();
									//LogUtil.v("queryFile","-------------------file--"
									//				+ file.getPath()+" filename:"+ fileName+" canRead:"+f.canRead());
//									if (file.getName().endsWith(".apk")) {
//										addApkInfo(file);
//									} else 
										if (fileName
											.endsWith(".doc")
											|| fileName
													.endsWith(".docx")
											|| fileName
													.endsWith(".xls")
											|| fileName
													.endsWith(".ppt")) {
										addDocInfo(file);
									}
									else if (fileName
													.endsWith(".pdf")
											|| fileName
													.endsWith(".txt")
											|| fileName
													.endsWith(".ebk3")
											|| fileName
													.endsWith(".jar")
											|| fileName
													.endsWith(".zip")) {
										addOtherInfo(file);
									}
									else if (file.getName().endsWith(".apk")) {
										addApkInfo(file);
									}
								} else if (file.isDirectory()
										&& file.listFiles().length > 0) {
									if ("Download".equals(file.getName())||"ctnq".equals(file.getName())) {
										getMyLocalFile(file);
									}
								}
							} catch (Exception e) {
								System.out.println("-------------------e--"
										+ e.getMessage());
							}

						}
					}
				}
			}
			}
		} catch (Exception e) {
			System.out.println("-------------------22222--" + e.getMessage());

		} finally {
			System.out.println("-------------------333333--");
		}
		LogUtil.v("queryFile","end<<<<<<<<<<<<<<<<<<<<usertime:"+(System.currentTimeMillis()-begintime));
	}

	private void addImgInfo(File file) {
		for (ImgPackInfo info : imgPackList) {
			if (info.getPackPath().equals(file.getParentFile().getPath())) {
				return;
			}
		}
		imgInfo = new ImgPackInfo();
		imgInfo.setPackName(file.getParentFile().getName());
		imgInfo.setPackPath(file.getParentFile().getPath());
		imgInfo.setIocPath(file.getPath());

		imgPackList.add(imgInfo);
	}

	private void addApkInfo(File file) {
		for (FileInfo info : apkList) {
			if (info.getPath().equals(file.getPath())) {
				return;
			}
		}
		FileInfo apkInfo = new FileInfo();
		apkInfo.setName(file.getName()
				.substring(0, file.getName().lastIndexOf(".")));
		apkInfo.setSize(FileMg.getFileSizes(file));
		apkInfo.setPath(file.getAbsolutePath());
		apkInfo.setFileType("apk");
		apkInfo.setTime(DateUtils.timeMillisToDateTimeString(file.lastModified(),DateUtils.FORMAT_5));
		//getApkFileInfo(apkInfo);
		LogUtil.v("queryFile","--------------------apk:" + apkInfo.getPath()+" "+apkInfo.getName());
		apkList.add(apkInfo);
	}

	/**
	 * 获取未安装的apk信息
	 * 
	 * @param ctx
	 * @param apkPath
	 * @return
	 */
	public void getApkFileInfo(FileInfo apkInfo) {
		LogUtil.v("queryFile","getApkFileInfo--------------apk:" + apkInfo.getPath()+" "+apkInfo.getName());
		File apkFile = new File(apkInfo.getPath());
		String PATH_PackageParser = "android.content.pm.PackageParser";
		String PATH_AssetManager = "android.content.res.AssetManager";
		try {
			// 反射得到pkgParserCls对象并实例化,有参数
			Class<?> pkgParserCls = Class.forName(PATH_PackageParser);
			Class<?>[] typeArgs = { String.class };
			Constructor<?> pkgParserCt = pkgParserCls.getConstructor(typeArgs);
			Object[] valueArgs = { apkInfo.getPath() };
			Object pkgParser = pkgParserCt.newInstance(valueArgs);

			// 从pkgParserCls类得到parsePackage方法
			DisplayMetrics metrics = new DisplayMetrics();
			metrics.setToDefaults();// 这个是与显示有关的, 这边使用默认
			typeArgs = new Class<?>[] { File.class, String.class,
					DisplayMetrics.class, int.class };
			java.lang.reflect.Method pkgParser_parsePackageMtd = pkgParserCls
					.getDeclaredMethod("parsePackage", typeArgs);

			valueArgs = new Object[] { new File(apkInfo.getPath()),
					apkInfo.getPath(), metrics, 0 };

			// 执行pkgParser_parsePackageMtd方法并返回
			Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(pkgParser,
					valueArgs);

			// 从返回的对象得到名为"applicationInfo"的字段对象
			if (pkgParserPkg == null) {
				return;
			}
			Field appInfoFld = pkgParserPkg.getClass().getDeclaredField(
					"applicationInfo");

			// 从对象"pkgParserPkg"得到字段"appInfoFld"的值
			if (appInfoFld.get(pkgParserPkg) == null) {
				return;
			}
			ApplicationInfo info = (ApplicationInfo) appInfoFld
					.get(pkgParserPkg);

			// 反射得到assetMagCls对象并实例化,无参
			Class<?> assetMagCls = Class.forName(PATH_AssetManager);
			Object assetMag = assetMagCls.newInstance();
			// 从assetMagCls类得到addAssetPath方法
			typeArgs = new Class[1];
			typeArgs[0] = String.class;
			java.lang.reflect.Method assetMag_addAssetPathMtd = assetMagCls
					.getDeclaredMethod("addAssetPath", typeArgs);
			valueArgs = new Object[1];
			valueArgs[0] = apkInfo.getPath();
			// 执行assetMag_addAssetPathMtd方法
			assetMag_addAssetPathMtd.invoke(assetMag, valueArgs);

			// 得到Resources对象并实例化,有参数
			Resources res = mContext.getResources();
			typeArgs = new Class[3];
			typeArgs[0] = assetMag.getClass();
			typeArgs[1] = res.getDisplayMetrics().getClass();
			typeArgs[2] = res.getConfiguration().getClass();
			Constructor<Resources> resCt = Resources.class
					.getConstructor(typeArgs);
			valueArgs = new Object[3];
			valueArgs[0] = assetMag;
			valueArgs[1] = res.getDisplayMetrics();
			valueArgs[2] = res.getConfiguration();
			res = (Resources) resCt.newInstance(valueArgs);

			// 读取apk文件的信息
			if (info != null) {
				LogUtil.v("queryFile","---------------------info.icon:"+info.icon);
				if (info.icon != 0) {// 图片存在，则读取相关信息
					Drawable icon = res.getDrawable(info.icon);// 图标
					apkInfo.setApkIoc(icon);
				}
				if (info.labelRes != 0) {
					String neme = (String) res.getText(info.labelRes);// 名字
					apkInfo.setName(neme);
				} else {
					String apkName = apkFile.getName();
					apkInfo.setName(apkName.substring(0,
							apkName.lastIndexOf(".")));
				}
				String pkgName = info.packageName;// 包名
				// 获取所有已安装程序的包信息
				System.out.println("---------------------pkgName:"
						+pkgName);
				apkInfo.setPackageName(pkgName);
				if(pinfo==null)
				 pinfo = mContext.getPackageManager()
						.getInstalledPackages(0);
				for (int i = 0; i < pinfo.size(); i++) {
					if (pinfo.get(i).packageName.equalsIgnoreCase(pkgName))
						return;
				}
				apkList.add(apkInfo);
			} else {
				return;
			}
		} catch (Exception e) {
			System.out.println("---------------------getMessage:"
					+ e.getMessage());
			e.printStackTrace();
		}
	}

	private void addDocInfo(File file) {
		for (FileInfo info : docList) {
			if (info.getPath().equals(file.getPath())) {
				return;
			}
		}
		LogUtil.v("queryFile","addDocInfo file:"+file.getPath());
		docInfo = new FileInfo();
		docInfo.setName(file.getName());
		docInfo.setSize(FileMg.getFileSizes(file));
		docInfo.setPath(file.getPath());
		docInfo.setFileType(file.getName().substring(
				file.getName().indexOf(".") + 1, file.getName().length()));
		docInfo.setTime(DateUtils.timeMillisToDateTimeString(file.lastModified(),DateUtils.FORMAT_5));
		docList.add(docInfo);
	}
	
	private void addOtherInfo(File file) {
		for (FileInfo info : otherFileList) {
			if (info.getPath().equals(file.getPath())) {
				return;
			}
		}
		//LogUtil.v("queryFile","addOtherInfo file:"+file.getPath());
		othreInfo = new FileInfo();
		othreInfo.setName(file.getName());
		othreInfo.setSize(FileMg.getFileSizes(file));
		othreInfo.setPath(file.getPath());
		othreInfo.setFileType(file.getName().substring(
				file.getName().indexOf(".") + 1, file.getName().length()));
		othreInfo.setTime(DateUtils.timeMillisToDateTimeString(file.lastModified(),DateUtils.FORMAT_5));
		otherFileList.add(othreInfo);
	}

	
	private void addVideoInfo(File file) {
		for (FileInfo info : mvList) {
			if (info.getPath().equals(file.getPath())) {
				return;
			}
		}
		videoInfo = new FileInfo();
		videoInfo.setName(file.getName().substring(0,
				file.getName().indexOf(".")));
		videoInfo.setSize(FileMg.getFileSizes(file));
		if (videoInfo.getSize() < 1000) {
			return;
		}
		videoInfo.setPath(file.getPath());
		videoInfo.setFileType(file.getName().substring(
				file.getName().indexOf(".") + 1, file.getName().length()));
		mvList.add(videoInfo);
	}

	private void addMusicInfo(File file) {
		for (FileInfo info : musicList) {
			if (info.getPath().equals(file.getPath())) {
				return;
			}
		}
		musicInfo = new FileInfo();
		musicInfo.setName(file.getName().substring(0,
				file.getName().indexOf(".")));
		musicInfo.setSize(FileMg.getFileSizes(file));
		if (musicInfo.getSize() < 1024 * 10) {
			return;
		}
		musicInfo.setPath(file.getPath());
		musicInfo.setFileType(file.getName().substring(
				file.getName().indexOf(".") + 1, file.getName().length()));
		System.out.println("-----------------getName-" + musicInfo.getName());
		musicList.add(musicInfo);
	}
	
	private void getMyLocalFile(File f) {
		if (f == null || !f.exists())
			return;
		if (f.isDirectory()) {
			File[] files1 = f.listFiles();
			for (int j = 0; j < files1.length; j++) {
				File cfile = files1[j];
				getMyLocalFile(cfile);
			}
		} else {
			fileName = f.getName();
			if (fileName.endsWith(".apk")) {
				addApkInfo(f);
			} else
				if (fileName.endsWith(".doc") || fileName.endsWith(".docx")
					|| fileName.endsWith(".xls") || fileName.endsWith(".ppt")) {
				addDocInfo(f);
			} else if (fileName.endsWith(".pdf") || fileName.endsWith(".txt")
					|| fileName.endsWith(".ebk3") || fileName.endsWith(".jar")
					|| fileName.endsWith(".zip")) {
				addOtherInfo(f);
			}
				
		}

	}

	
	File sdCardFile=Environment.getExternalStorageDirectory();
	private void getLocalSdCardApk(File f) {
		if (f == null || !f.exists())
			return;
		if (f.isDirectory()) {
			File[] files1 = f.listFiles();
			if(files1!=null){
			for (int j = 0; j < files1.length; j++) {
				File cfile = files1[j];
				getLocalSdCardApk(cfile);
			}
			}
		} else {
			fileName = f.getName();
			if (fileName.endsWith(".apk")) {
				addApkInfo(f);
			}
		}
	}
}
